import 'dart:convert';
import 'dart:io';

import 'package:aichat_flutter_wallet/module/module_wallet/pages/wallet_custom_token.dart';
import 'package:aichat_flutter_wallet/module_common/utils/util.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/button/public_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_util/lib_util.dart';

import '../../../module_common/model/chain_lists_model.dart';
import '../../../module_common/provider/token_list_provider.dart';
import '../../../module_common/provider/wallet_info_provider.dart';
import '../../../module_common/router/routers.dart';
import '../../../module_common/widgets/header/page_header.dart';
import '../../../module_common/widgets/image/public_image.dart';
import '../../../module_common/widgets/text_high_light.dart';
import '../../../module_common/widgets/token_widget/token_logo.dart';

class WalletAddToken extends StatefulWidget {
  const WalletAddToken({Key? key}) : super(key: key);

  @override
  _WalletAddTokenState createState() => _WalletAddTokenState();
}

class _WalletAddTokenState extends State<WalletAddToken> {
  TextEditingController _textEditingController = TextEditingController();
  FocusNode _focusNode = FocusNode();
  final GlobalKey _searchCloseKey = GlobalKey();

  @override
  void initState() {
    super.initState();

    //初始化
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      context.read<TokenListNotifier>().resetSearchText();
      initPopularTokensFromSP();
    });
  }

  @override
  void dispose() {
    _textEditingController.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: PageHeaderCom(
          title: String.fromEnvironment('emailString',
              defaultValue: 'Token Management'),
          showBottomBorder: false,
        ),
        bottomNavigationBar: bottomControl(),
        body: Container(
            color: Colors.white,
            child: Column(children: [
              Padding(
                  padding: EdgeInsets.fromLTRB(20.w, 0, 20.w, 0),
                  child: searchTextFieldBar()),
              Expanded(
                  child: Padding(
                      padding: EdgeInsets.fromLTRB(
                          0, 0, 0, MediaQuery.of(context).padding.bottom),
                      child: reorderableList(context))),
            ])));
  }

  //搜索点击框
  Widget searchTextFieldBar({List<TextInputFormatter>? inputFormatters}) {
    return Container(
      height: 40.w,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10.w),
          color: '#F6F6F6'.toColor()),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(width: 15.w),
          Image.asset(
            'assets/images/dapp/search.png',
            width: 20.w,
            height: 20.w,
          ),
          SizedBox(width: 10.w),
          Expanded(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Expanded(
                    child: Stack(children: [
                  TextField(
                    style: TextStyle(fontSize: 14.0.sp,textBaseline: TextBaseline.ideographic,
                      height: 1.1
                    ),
                    cursorHeight: 16.w,
                    controller: _textEditingController,
                    focusNode: _focusNode,
                    inputFormatters: inputFormatters,
                    maxLines: 1,
                    minLines: 1,
                    cursorColor: Color.fromRGBO(134, 103, 254, 1),
                    cursorWidth: 1.5.w,
                    onChanged: (value) {
                      context
                          .read<TokenListNotifier>()
                          .searchListWithText(value);
                      setState(() {});
                    },
                    onTapOutside: (even) {
                      //拿到删除按钮，判断点击的是否删除按钮，是的话不需要收起软键盘
                      final RenderBox? referenceBox =
                          _searchCloseKey.currentContext?.findRenderObject()
                              as RenderBox?;
                      final Offset? pos =
                          referenceBox?.globalToLocal(even.localPosition);
                      bool? within = referenceBox?.hitTest(BoxHitTestResult(),
                          position: pos!);
                      if (within == false) {
                        //这里先注释掉，因为点击添加和删除也算是点击外部，收起键盘的话界面会产生叫突兀的变化
                        // _focusNode.unfocus();
                      }
                    },
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: 'Search token name',
                      contentPadding: EdgeInsets.only(bottom: 5.w),
                      hintStyle: TextStyle(
                        fontSize: 14.sp,
                          height: 1.05,
                          textBaseline: TextBaseline.ideographic,
                        color: Color.fromRGBO(190, 189, 202, 1),
                      ),
                    ),
                  )
                ])),
              ],
            ),
          ),
          Consumer<TokenListNotifier>(// 使用 Consumer 来监听状态更改并重新构建此部分的 widget 树。
              builder: (context, model, child) {
            return Visibility(
                key: _searchCloseKey,
                visible: !model.searchText.isEmpty,
                child: GestureDetector(
                  onTap: () {
                    context.read<TokenListNotifier>().resetSearchText();
                    _textEditingController.clear();
                  },
                  child: Container(
                    width: 36.w,
                    height: 36.w,
                    padding: EdgeInsets.only(left: 10.w, right: 10.w),
                    child: Image.asset(
                      'assets/images/dapp/history_input_close.png',
                    ),
                  ),
                ));
          })
        ],
      ),
    );
  }

  Widget trendingRow(int index, String title) {
    return Container(
      key: Key("${index}"),
      height: 40.w,
      margin: EdgeInsets.only(top: 10.w),
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(title,
              style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                  color: "#333333".toColor())),
        ],
      ),
    );
  }

  Widget bottomControl() {
    return Container(
        margin: EdgeInsets.only(bottom: Platform.isIOS ? 49.w : 10.w),
        child: PublicButton(
          image: Image.asset(
            'assets/images/common/edit.png',
            height: 16.w,
            width: 16.w,
          ),
          text: 'Custom Tokens',
          hasHov: false,
          onClick: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => WalletCustomToken(),
                settings: RouteSettings(name: Routes.walletCustomToken),
              ),
            ).then((value) {
                popularTokens = [];
                initPopularTokensFromSP();
                setState(() {
                });
            });
            // Routes.navigateTo(
            //   context,
            //   Routes.walletCustomToken,
            // );
          },
        ));
  }

  //每次进入页面的时候从SP拿数据初始化
  void initPopularTokensFromSP() {
    List<dynamic> list = SP().getKeyTokenList();
    //拿到已添加的代币地址
    var addedList = context
        .read<TokenListNotifier>()
        .tokenFungibleList
        .map((e) => e.contract.toLowerCase());
    //当前chainID
    var chainID = context
        .read<WalletInfoNotifier>()
        .walletInfo!
        .getChain()!
        .evmInfo!
        .chainId;

    list.forEach((jsonString) {
      var json = jsonDecode(jsonString);
      var tokenObj = TokensObjModel.fromJson(json);
      //提出不同chainID的token
      if (chainID.toString() != tokenObj.chain_id) {
        return;
      }
      //网络Token类型，转本地数据库的Token
      Token token = Token(
        walletInfoId: context.read<TokenListNotifier>().walletInfoId,
        contractType: TokenType.token20.name,
        contract: tokenObj.contract_address,
        name: tokenObj.name.toString(),
        symbol: tokenObj.symbol.toString(),
        logo: tokenObj.icon,
        decimals: int.parse(tokenObj.decimal),
        balance: '0.00',
        valueusd: '0.00',
        change24h: '0.00',
        enable: true,
        isAdded: addedList.contains(tokenObj.contract_address.toLowerCase()),
      );
      popularTokens.add(token);
    });
  }

  List<Token> getSystemTokenList() {
    var list =
        popularTokens.where((element) => element.isAdded == false).toList();
    return list;
  }

  List<Token> popularTokens = [];
  //拖拽列表
  Widget reorderableList(BuildContext context) {
    return Consumer<TokenListNotifier>(builder: (context, provider, child) {
      //这里就要处理
      //1、首先拿到已添加的
      var addList = provider.tokenFungibleList;
      //2、然后拿到后台定义的，未添加的token
      var customList = getSystemTokenList();
      //3、添加多一行数据，用于展示标题。在已添加前加一个。在后台定义前加一个(如果是搜索的话，那就不需要添加了)
      List<Token> totalList;
      if (provider.searchText.isEmpty) {
        var trendingItem = Token(
            walletInfoId: 0,
            contractType: '',
            contract: '',
            name: 'Popular Token',
            symbol: '');
        var addedItem = Token(
            walletInfoId: 0,
            contractType: '',
            contract: '',
            name: 'Added Token',
            symbol: '');

        totalList = addList + customList;
        if (customList.isNotEmpty) {
          totalList.insert(addList.length, trendingItem);
        }
        if (addList.isNotEmpty) {
          totalList.insert(0, addedItem);
        }
      } else {
        var tempAddList = addList.where((element) {
          var regExp = RegExp('${provider.searchText}', caseSensitive: false);
          return regExp.hasMatch(element.getShowName());
        }).toList();
        var tempCustomList = customList.where((element) {
          var regExp = RegExp('${provider.searchText}', caseSensitive: false);
          return regExp.hasMatch(element.getShowName());
        }).toList();

        totalList = tempAddList + tempCustomList;
      }

      return ReorderableListView.builder(
          shrinkWrap: true,
          buildDefaultDragHandles: false, //这是为false，使用自定义拖拽
          onReorder: (int oldIndex, int newIndex) {
            //因为拖拽的时候可以拖到不允许拖拽的row，所以这里还要判断一下
            if (newIndex == 0 || oldIndex == newIndex) {
              return;
            }
            if (oldIndex < newIndex) {
              //因为先删除，所以old小于new的话，删除后要向前一个位置
              if (totalList[newIndex - 1].isAdded == false) {
                return;
              }
            } else {
              if (totalList[newIndex].isAdded == false) {
                return;
              }
            }

            //因为加了一行组头，所以这里的index都要减一
            provider.reorderTokens(oldIndex - 1, newIndex - 1);
          },
          itemCount: totalList.length,
          itemBuilder: (context, index) {
            if (provider.searchText.isEmpty) {
              //说明
              if (totalList[index].name == 'Popular Token') {
                return trendingRow(index, totalList[index].name);
              } else if (totalList[index].name == 'Added Token') {
                return trendingRow(index, totalList[index].name);
              } else {}
            } else {}

            return _buildListItem(context, totalList[index], index,
                isShowSragEnable:
                    totalList[index].isAdded && provider.searchText.isEmpty,
                provider: provider);
          },
          proxyDecorator:
              (Widget child, int index, Animation<double> animation) {
            return AnimatedBuilder(
              animation: animation,
              builder: (BuildContext context, Widget? child) {
                return Material(
                  elevation: 0,
                  color: Colors.transparent,
                  child: child,
                );
              },
              child: Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    boxShadow: [
                      BoxShadow(
                        color: Color.fromRGBO(0, 0, 0, 0.09),
                        offset: Offset(0, 2.w),
                        blurRadius: 5.w,
                        spreadRadius: 1.w,
                      ),
                    ],
                  ),
                  child: child),
            );
          });
    });
  }

  Widget _buildListItem(BuildContext context, Token item, int index,
      {bool isShowSragEnable = true, required TokenListNotifier provider}) {
    return Container(
      key: Key("${index}"),
      padding: EdgeInsets.only(left: 18.w, right: 18.w),
      height: 60.w,
      child: ReorderableDragStartListener(
        enabled: isShowSragEnable,
        //这个是拖拽的关键
        index: index,
        child: Row(
          children: [
            SizedBox(width: 8.w),
            Stack(
              clipBehavior: Clip.none,
              children: [
                TokenLogo(
                  token: item,
                  size: 40.w,
                ),
                Visibility(
                    visible: item.contractType != TokenType.native.name,
                    child: Positioned(
                      right: -3.w,
                      bottom: -1.w,
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(16.w),
                        child: PublicImage(
                            width: 16.w,
                            height: 16.w,
                            image: context
                                .read<WalletInfoNotifier>()
                                .walletChain!
                                .logo),
                      ),
                    ))
              ],
            ),
            SizedBox(width: 12),
            Expanded(
              child: Consumer<TokenListNotifier>(
                  // 使用 Consumer 来监听状态更改并重新构建此部分的 widget 树。
                  builder: (context, model, child) {
                return TextHighlight(
                  item.getShowName().toUpperCase(),
                  model.searchText.toString().isEmpty ? [] : [model.searchText],
                  TextStyle(
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w500,
                      color: Color.fromRGBO(51, 51, 51, 1)),
                  TextStyle(
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w500,
                      color: Color.fromRGBO(134, 103, 254, 1)),
                  caseSensitive: false,
                );
              }),
            ),
            InkWell(
                child: Image.asset(
                  item.isAdded
                      ? 'assets/images/wallet/token_delete.png'
                      : 'assets/images/wallet/token_add.png',
                  width: 20.w,
                  height: 20.w,
                ),
                onTap: () {
                  if (item.isCustom) {
                    provider.deleteTokens(item);
                  }
                  item.isAdded = !item.isAdded;
                  //因为后台配置的token是存在SP中的，所以更新状态的时候还要处理当前的数据
                  Token? token = popularTokens.firstWhereOrNull(
                      (element) => element.contract.toLowerCase() == item.contract.toLowerCase());
                  token!.isAdded = item.isAdded;
                  if (item.isAdded) {
                    //真实的从数据库中添加、删除
                    //添加
                    provider.addToken(item);
                  } else {
                    //删除
                    provider.deleteTokens(item);
                  }
                }),
            Visibility(
              visible: isShowSragEnable,
              child: Padding(
                padding: EdgeInsets.only(left: 15.w),
                child: Image.asset(
                  'assets/images/wallet/token_order.png',
                  width: 20.w,
                  height: 20.w,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
